import type {AxiosRequestConfig, AxiosResponse} from "axios";
import axios from 'axios'
import {ElMessage} from 'element-plus'
import {appConfig} from '@/config/AppConfig'
import {ErrorCode, handleError} from '@/enum/ErrorCode'
import {tokenStore} from '@/store/userStore.ts'

const httpConfig = appConfig().httpConfig

/**
 * 创建请求实例
 */
const http = axios.create({
  // 请求基础地址
  baseURL: httpConfig.baseURL,
  // 请求超时时间，默认60s
  timeout: httpConfig.timeout,
  // 请求头参数配置
  headers: httpConfig.headers
})

// 添加请求拦截器 在发请求之前处理一下
http.interceptors.request.use((config: any) => {
  const tokenStoreData = tokenStore()
  if(tokenStoreData.token){
    config.headers['token'] = `${tokenStoreData.token}`
  }
  return config
}, (error:any) => {
  ElMessage.error(error.message)
  return Promise.reject(error)
})

// 添加响应拦截器 在得到数据之后处理一下
http.interceptors.response.use((response: AxiosResponse) => {
  if(response instanceof Blob){
    return response
  }

  const data = response.data as Result
  handleError(data)

  return Promise.reject(data)
}, (error) => {
  ElMessage.error(error.message)
  return Promise.reject(error);
})

/**
 * 请求响应数据体
 */
export type Result<T = any> = {
  msg: string
  code: ErrorCode
  data: T,
  total: number
}

export default <T> (config: AxiosRequestConfig) => {
  return new Promise<Result<T>>((resolve) => {
    http.request<Result<T>>(config).then((response: AxiosResponse<Result<T>>) => {
      resolve(response.data)
    }).catch((error : Result) => {
      resolve(error)
    })
  })
}